package cn.wolfcode.car.web.controller;


import cn.wolfcode.car.domain.Role;
import cn.wolfcode.car.service.IPermissionService;
import cn.wolfcode.car.service.IRoleService;
import cn.wolfcode.car.qo.QueryObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list";
    }


    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
           roleService.delete(id);
        }
        return "redirect:/role/list";
    }


    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] permissionIds) {
        if (role.getId() == null) {
            roleService.save(role, permissionIds);
        } else {
            roleService.update(role, permissionIds);
        }
        return "redirect:/role/list";
    }


    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("role",roleService.get(id));
        }
        model.addAttribute("permissions", permissionService.listAll());
        return "role/input";
    }
}
